const Router = require('koa-router')
const { TokenValidator, NotEmptyValidator } = require('../../validators/validator.js')
const { LoginType } = require('../../lib/enum.js')
const User = require('../../models/user.js')
const { generateToken } = require('../../../core/util.js')
const {
  Auth
} = require('../../../middlewares/auth')
const router = new Router({
  prefix: '/v1/token'
})

const WXManager = require('../../service/wx.js')

router.post('/', async (ctx) => {
  const v = await new TokenValidator().validate(ctx)
  // 业务逻辑
  // 1.Api中编写
  // 2.model 分层

  let token
  switch (v.get('body.type')) {
    case LoginType.USER_EMAIL:
      token = await emailLogin(v.get('body.account'), v.get('body.secret'))
      break;
    case LoginType.USER_MINI_PROGRAM:
      token = await WXManager.codeToToKen(v.get('body.account'))
        break;
    default: 
      throw new global.errs.ParameterException('没有相应的处理函数！')
  }
  ctx.body = {
    token
  }
})

router.post('/verify', async (ctx) => {
  // token
  const v = await new NotEmptyValidator().validate(ctx)
  const result = Auth.verifyToken(v.get('body.token'))
  ctx.body = {
    is_valid: result
  }

})


async function emailLogin(account, secret) {
  // jw 
  const user = await User.verifyEmailPassword(account, secret)
  return token = generateToken(user.id, Auth.USER)
}

module.exports = router